package graph;

import java.util.Arrays;

//利用邻接矩阵存储图
public class GraphByMatrix {
    private char[] arrV;//顶点数组
    private int[][] matrix;//邻接矩阵
    private boolean isDirect;//是否是有向图

    public GraphByMatrix(int size,boolean isDirect){
        //size代表当前顶点个数
        this.arrV=new char[size];
        this.matrix=new int[size][size];
        for (int i = 0; i < size; i++) {
            Arrays.fill(matrix[i],Constant.MAX);//初始化都置为∞
        }
        this.isDirect=isDirect;
    }
    public void initArrV(char[] arr){
        for (int i = 0; i < arrV.length; i++) {
            arrV[i]=arr[i];
        }
    }
    //添加边
    //srcV-起点 destV-终点 weight-权值
    public void addEdge(char srcV,char destV,int weight){
        int srcIndex=getIndexOfV(srcV);
        int destIndex=getIndexOfV(destV);
        matrix[destIndex][srcIndex]=weight;
        //如果是无向图，也需要在相反的方向置为空
        if(!isDirect){
            matrix[srcIndex][destIndex]=weight;
        }

    }
    //获取顶点v的下标
    private int getIndexOfV(char v){
        for (int i = 0; i < arrV.length; i++) {
            if(arrV[i]==v){
                return i;
            }
        }
        return -1;
    }
    //获取顶点v的度 (如果是有向图，则度=入度+出度）
    public int getDevOfV(char v){
        int count=0;
        int srcIndex=getIndexOfV(v);
        for (int i = 0; i < arrV.length; i++) {
            if(matrix[srcIndex][i]!=Constant.MAX){
                count++;
            }
        }
        //计算有向图的入度
        if(isDirect){
            for (int i = 0; i < arrV.length; i++) {
                if(matrix[i][srcIndex]!=Constant.MAX){
                    count++;
                }
            }
        }
        return count;
    }
    //打印矩阵
    public void printGraph(){
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                if(matrix[i][j]==Constant.MAX){
                    System.out.print("∞ ");
                }else{
                    System.out.print(matrix[i][j]+" ");
                }
            }
            System.out.println();
        }
    }
}
